package com.hxzy.dao.Impl;

import com.hxzy.bean.Film;
import com.hxzy.bean.HotFilm;
import com.hxzy.dao.HotFilmDao;
import com.hxzy.service.FilmService;
import com.hxzy.service.Impl.FilmServiceImpl;
import com.hxzy.util.JdbcUtils;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class HotFilmDaoImpl implements HotFilmDao {
    @Override
    public int save(HotFilm hotFilm) {
        String sql = "INSERT INTO hotfilms (film_id,hottime,weight,state) VALUES(?,?,?,?)";
        Object[] params={hotFilm.getFilm().getfId(),hotFilm.getTime(),hotFilm.getWeight(),hotFilm.getState()};
        return JdbcUtils.executeUpdate(sql,params);
    }

    @Override
    public int update(HotFilm hotFilm) {
        String sql="UPDATE hotfilms set film_id=?,hottime=?,weight=?,state=? WHERE id=?";
        Object[] params = {hotFilm.getFilm().getfId(), hotFilm.getTime(), hotFilm.getWeight(), hotFilm.getState(), hotFilm.getId()};
        return JdbcUtils.executeUpdate(sql,params);
    }

    @Override
    public int remove(Integer integer) {
        String sql="DELETE FROM hotfilms WHERE id=?";
        return JdbcUtils.executeUpdate(sql,integer);
    }

    @Override
    public List<Map<String, Object>> queryAll() {
        String sql ="SELECT id,film_id fid,hottime time,weight,state FROM hotfilms";
        return JdbcUtils.executeQuery(sql);
    }

    @Override
    public HotFilm findByID(Integer integer) {
        FilmService service=new FilmServiceImpl();
        String sql="SELECT id,film_id fid,hottime time,weight,state FROM hotfilms WHERE id=?";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql, integer);
        Optional<HotFilm> first = list.stream().map(t -> {
            int id = (int) t.get("id");
            int fid = (int) t.get("fid");
            Film film = service.findByID(fid);
            Timestamp time = (Timestamp) t.get("time");
            LocalDateTime localDateTime = time.toLocalDateTime();
            int weight = (int) t.get("weight");
            int state = (int) t.get("state");
            return new HotFilm(id, film, localDateTime, weight, state);
        }).findFirst();
        return first.orElse(null);
    }
}
